<template>
  <el-dialog
      v-model="dialogVisible"
      title="编辑销售单"
      width="900px"
      :before-close="handleClose"
      class="SalesOrderEdit"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" class="SalesOrderEdit-form">
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="订单编号" prop="orderNo">
            <div class="SalesOrderEdit-form-orderNo">
              <el-input v-model="form.orderNo" placeholder="请输入订单编号" class="SalesOrderEdit-form-orderNo-input"/>
              <el-button type="primary" class="SalesOrderEdit-form-orderNo-btn" @click="generateOrderNo">随机生成
              </el-button>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户" prop="customerId">
            <el-select v-model="form.customerId" placeholder="请选择客户" filterable clearable
                       class="SalesOrderEdit-form-input">
              <el-option v-for="c in customerList" :key="c.id" :label="c.name" :value="c.id"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="下单日期">
            <el-input :model-value="form.orderDate" disabled class="SalesOrderEdit-form-input"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="备注">
            <el-input v-model="form.note" placeholder="可填写备注" class="SalesOrderEdit-form-input"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-alert title="当前仅允许修改基础信息，明细不可在此编辑。" type="info" :closable="false"
              class="SalesOrderEdit-tip"/>

    <el-table :data="items" border stripe class="SalesOrderEdit-table">
      <el-table-column type="index" label="#" width="60" align="center"/>
      <el-table-column prop="code" label="商品编码" min-width="120" align="center"/>
      <el-table-column prop="name" label="商品名称" min-width="160" align="center"/>
      <el-table-column prop="unit" label="单位" width="100" align="center"/>
      <el-table-column prop="quantity" label="数量" width="120" align="center"/>
      <el-table-column prop="unitPrice" label="单价(¥)" width="120" align="center">
        <template #default="{row}">{{ formatMoney(row.unitPrice) }}</template>
      </el-table-column>
      <el-table-column prop="totalPrice" label="小计(¥)" width="140" align="center">
        <template #default="{row}">{{ formatMoney(row.totalPrice) }}</template>
      </el-table-column>
    </el-table>

    <div class="SalesOrderEdit-summary">
      <div class="SalesOrderEdit-summary-row">
        <div class="SalesOrderEdit-summary-label">合计金额：</div>
        <div class="SalesOrderEdit-summary-value">¥ {{ formatMoney(totalAmount) }}</div>
      </div>
    </div>

    <template #footer>
      <div class="SalesOrderEdit-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="saving" @click="handleSave">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import {ref, reactive, watch, computed} from 'vue'
import {ElMessage} from 'element-plus'
import {getSalesOrder, updateSalesOrder} from '../../../../api/salesOrderApi.js'
import {listCustomers} from '../../../../api/customerApi.js'

const props = defineProps({visible: {type: Boolean, default: false}, orderId: {type: Number, default: null}})
const emits = defineEmits(['update:visible', 'success'])

const dialogVisible = ref(false)
const formRef = ref()
const form = reactive({id: null, orderNo: '', customerId: null, orderDate: '', note: ''})
const items = ref([])
const customerList = ref([])
const saving = ref(false)

const rules = reactive({
  orderNo: [{required: true, message: '请输入订单编号', trigger: 'blur'}],
  customerId: [{required: true, message: '请选择客户', trigger: 'change'}]
})

watch(() => props.visible, v => {
  dialogVisible.value = v;
  if (v && props.orderId) init()
})
watch(dialogVisible, v => {
  if (!v) emits('update:visible', false)
})

const init = async () => {
  await Promise.all([loadCustomers(), loadDetail()])
}

const loadCustomers = async () => {
  try {
    const res = await listCustomers({condition: {}});
    customerList.value = res.list || []
  } catch (e) {
    ElMessage.error('加载客户失败')
  }
}
const loadDetail = async () => {
  try {
    const res = await getSalesOrder(props.orderId)
    if (res) {
      form.id = res.id
      form.orderNo = res.orderNo
      form.customerId = res.customerId
      form.orderDate = res.orderDate
      form.note = res.note
      items.value = res.items || []
    }
  } catch (e) {
    ElMessage.error('获取详情失败')
  }
}

const totalAmount = computed(() => items.value.reduce((a, c) => a + Number(c.totalPrice || 0), 0))
const handleClose = () => {
  dialogVisible.value = false
}
const handleSave = async () => {
  try {
    await formRef.value?.validate();
    saving.value = true;
    const payload = {id: form.id, orderNo: form.orderNo, customerId: form.customerId, note: form.note}
    await updateSalesOrder(payload)
    ElMessage.success('保存成功')
    emits('success')
    dialogVisible.value = false
  } catch (e) { /* ignore */
  } finally {
    saving.value = false
  }
}
const formatMoney = v => Number(v || 0).toFixed(2)
const generateOrderNo = () => {
  const code = Math.floor(Math.random() * 100000000).toString().padStart(8, '0');
  form.orderNo = code;
  ElMessage.success('已生成: ' + code)
}
</script>
<style scoped lang="scss">
.SalesOrderEdit {
  &-form {
    padding: 16px 0;

    &-input {
      width: 100%;
    }

    &-orderNo {
      display: flex;
      gap: 8px;
      align-items: center;

      &-input {
        flex: 1;
      }

      &-btn {
        flex: 0 0 auto;
      }
    }
  }

  &-tip {
    margin-bottom: 16px;
  }

  &-table {
    width: 100%;
    margin-top: 8px;
  }

  &-summary {
    display: flex;
    justify-content: flex-end;
    padding: 16px 0;

    &-row {
      display: flex;
      gap: 8px;
      align-items: center;
    }

    &-label {
      font-size: 14px;
      color: #606266;
    }

    &-value {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
    }
  }

  &-footer {
    display: flex;
    justify-content: flex-end;
    gap: 8px;
  }
}
</style>
